/*
 * Copyright 2009-2010 Belmont Software Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.belmont.backup;

import java.util.*;
import java.io.*;

public class FileStorage implements IBackupConstants {
    static final boolean DEBUG = false;
    static final int DIR_LENGTH = 4;
    static int DIR_PARTS = (DIGEST_ALGORITHM_LENGTH / DIR_LENGTH);
    static Hashtable<String, FileStorage> stores = new Hashtable<String, FileStorage>();
    File root;
    Hashtable<String, SFile> cache = new Hashtable<String, SFile>();

    public static synchronized FileStorage getStorage(String path) {
	FileStorage store = stores.get(path);

	if (store == null) {
	    store = new FileStorage(new File(path));
  	    stores.put(path, store);
	}

	return store;
    }

    private FileStorage(File root) {
	this.root = root;
    }

    public void deleteFiles() {
	Utils.log(LOG_INFO, "FileStorage deleteFiles");
	cache.clear();
    }

    public SFile getFileCreate(String digest) throws IOException {
	return getFile(digest, true);
    }

    public SFile get(String digest) throws IOException {
	return getFile(digest, false);
    }

    boolean checkDir(File dir, boolean create) {
	if (dir.isDirectory()) {
	    return true;
	}
	return (create) ? dir.mkdirs() : false;
    }

    File getDirForDigest(String digest, boolean create) {
	File dir = new File(root, "files"+File.separator+digest.substring(0, DIR_PARTS - 1));

	if (!checkDir(dir, create)) {
	    return null;
	}

	for (int i=DIR_PARTS; i < DIGEST_ALGORITHM_LENGTH; i+=DIR_PARTS) {
	    dir = new File(dir, digest.substring(i, i+DIR_PARTS - 1));
	    if (!checkDir(dir, create)) {
		return null;
	    }
	}

	return dir;
    }

    public synchronized void delete(SFile sf) {
	cache.remove(sf.digest);
	Utils.delete(sf.dir);
    }

    public synchronized SFile getFile(String digest, boolean create) throws IOException {
	if (digest == null || digest.length() != DIGEST_ALGORITHM_LENGTH) {
	    throw new IllegalArgumentException("digest parameter is bad: "+digest);
	}

	SFile f = cache.get(digest);

	if (f != null) {
	    return f;
	}

	File dir = getDirForDigest(digest, create);

	if (dir == null) {
	    return null;
	}

	f = new SFile(dir, digest);
	f.init();
	//cache.put(digest, f);

	return f;
    }
}